<script setup>
  import { useNavbarHeight } from '@/composables/useNavbarHeight'
  import { computed, ref } from 'vue'
  import { FILTER_LIST, FILTER_MAP, OSS_BASE_URL } from '@/contants/home'

  import filterByType from '@/pages/index/components/filter/filter-by-type.vue'
  import filterByArea from '@/pages/index/components/filter/filter-by-area.vue'
  import filterByPrice from '@/pages/index/components/filter/filter-by-price.vue'
  import filterBySort from '@/pages/index/components/filter/filter-by-sort.vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { getFilterPullListApi, getHouseListApi } from '@/api/home'
  import { useLocationStore } from '@/stores'
  import { normalize } from '@/utils/normalize'
  import { getLongitudeAndLatitude } from '@/utils/getLocation'
  const locationStore = useLocationStore()
  const { NAV_BAR_HEIGHT } = useNavbarHeight()

  const SCROLL_VIEW_TOP = computed(() => {
    return NAV_BAR_HEIGHT.value + uni.upx2px(108)
  })

  const currentRentType = ref('')

  // 控制弹层可见
  const visible = ref(false)
  // 当前操作类型
  const opsType = ref('')

  // 区域列表
  const regionList = ref([])
  // 租金列表
  const rentRangeList = ref([])
  // 出租方式列表
  const rentTypeList = ref([])
  // 房屋数量列表
  const roomNumList = ref([])

  const areaRef = ref(null)
  const priceRef = ref(null)
  const houseTypeRef = ref(null)
  // 选择的区域
  const selectedRegion = ref({})
  // 选择的租金列表
  const selectedRentRangeList = ref([])
  // 选择的出租方式列表
  const selectedRentTypeList = ref([])
  // 选择的房屋数量列表
  const selectedRoomNumList = ref([])
  // 选择的排序规则
  const selectedSort = ref({})

  // 获取筛选下拉列表
  async function getFilterPullList() {
    if (rentRangeList.value.length > 0) return
    const resp = await getFilterPullListApi({
      cityId: locationStore.location.id,
      dirtTypes: ['rent_range', 'rent_type_list', 'room_num']
    })
    regionList.value = normalize(resp.regionList)
    rentRangeList.value = normalize(resp.dictMap.rent_range)
    rentTypeList.value = normalize(resp.dictMap.rent_type_list).map((item) => ({
      ...item,
      isSelected: item.key === currentRentType.value
    }))
    roomNumList.value = normalize(resp.dictMap.room_num)
  }
  onLoad((query) => {
    currentRentType.value = query.rentType
    getFilterPullList()
    getHouseList()
  })
  // 打开弹出层
  const onOpen = (item) => {
    FILTER_LIST.value.forEach((item) => {
      item.isOpen = false
    })
    // 同步操作类型
    opsType.value = item.key
    // 取反
    item.isOpen = true
    // 打开弹出层
    visible.value = true
  }

  let isFinished = false
  // 点击确定时
  const onConfirm = (e) => {
    isLoading.value = true
    pageQuery.pageNo = 1
    houseList.value = []
    isFinished = false
    switch (opsType.value) {
      case FILTER_MAP.AREA:
        const index = areaRef.value.currentIndex
        selectedRegion.value = regionList.value[index] || []
        break
      case FILTER_MAP.RENT_PRICE:
        selectedRentRangeList.value = priceRef.value.selectedPriceList
        break
      case FILTER_MAP.HOUSE_TYPE:
        selectedRentTypeList.value = houseTypeRef.value.selectedRentList
        console.log('selectedRentTypeList', selectedRentTypeList.value)
        currentRentType.value = selectedRentTypeList.value.length > 0 ? selectedRentTypeList.value[0].key : null
        selectedRoomNumList.value = houseTypeRef.value.selectedRoomList
        break
      case FILTER_MAP.SORT:
        selectedSort.value = e
        break
    }
    // 箭头置于关闭态
    FILTER_LIST.value.forEach((item) => {
      if (item.isOpen) {
        item.isOpen = false
      }
    })
    // 关闭弹出层
    visible.value = false

    // 请求房源列表
    getHouseList()
  }

  const pageQuery = {
    pageNo: 1, // 页码
    pageSize: 10 // 条数
  }
  // 房源列表
  const houseList = ref([])
  // 是否在请求中
  const isLoading = ref(true)
  // 获取房源列表
  async function getHouseList() {
    // 处理选中的值，符合接口格式
    const cityId = locationStore.location.id
    const regionId = selectedRegion.value.id || null
    const rentalRanges = selectedRentRangeList.value.filter((item) => item.key !== null).length
      ? selectedRentRangeList.value.map((item) => item.key)
      : null
    const rentTypes =
      selectedRentTypeList.value.filter((item) => item.key !== null).length > 0
        ? selectedRentTypeList.value.map((item) => item.key)
        : [currentRentType.value]
    const rooms = selectedRoomNumList.value.filter((item) => item.key !== null).length
      ? selectedRoomNumList.value.map((item) => item.key)
      : null
    const sort = selectedSort.value.key || 'distance'
    let latitude = null
    let longitude = null
    if (!locationStore.location.latitude || !locationStore.location.longitude) {
      const resp = await getLongitudeAndLatitude()
      latitude = resp.latitude
      longitude = resp.longitude
    } else {
      latitude = locationStore.location.latitude
      longitude = locationStore.location.longitude
    }
    // 调用接口，请求房源列表
    const { list, totalPages } = await getHouseListApi({
      cityId,
      regionId,
      rentalRanges,
      rentTypes,
      rooms,
      sort,
      longitude,
      latitude,
      ...pageQuery
    })
    // 没有数据了
    if (pageQuery.pageNo > totalPages || list.length <= 0) {
      isFinished = true
      uni.showToast({
        title: '没有更多数据了',
        icon: 'none'
      })
      isLoading.value = false
    } else {
      // 合并房源列表
      houseList.value = [
        ...houseList.value,
        ...list.map((item) => ({
          ...item,
          headImage: OSS_BASE_URL + item.headImage
        }))
      ]
      isLoading.value = false
    }
  }

  // 出租方式显示的名称
  const rentTypeName = computed(() => {
    if (currentRentType.value === null) return null
    const temp = rentTypeList.value.find((item) => item.key === currentRentType.value)
    return temp ? temp.name : null
  })
  // 区域是否选择了
  const isRegionActive = computed(() => {
    return Object.keys(selectedRegion.value).length > 0 && selectedRegion.value.id !== 0
  })

  // 租金是否选择了
  const isRentPriceActive = computed(() => {
    return selectedRentRangeList.value.filter((item) => item.id !== 0).length > 0
  })

  // 户型是否选择了
  const isHouseTypeActive = computed(() => {
    return (
      currentRentType.value !== null ||
      selectedRentTypeList.value.filter((item) => item.id !== 0).length > 0 ||
      selectedRoomNumList.value.filter((item) => item.id !== 0).length > 0
    )
  })
  // 排序是否选择了
  const isSortActive = computed(() => {
    return !!Object.keys(selectedSort.value).length && selectedSort.value.key !== 'distance'
  })

  // 弹层关闭时
  const onPopupClose = () => {
    FILTER_LIST.value.forEach((item) => {
      if (item.isOpen) {
        item.isOpen = false
      }
    })
  }

  // 上下触底时
  const onReachBottom = () => {
    if (isLoading.value || isFinished) return
    pageQuery.pageNo++
    getHouseList()
  }

  // 默认房源头图
  const defaultImage = 'https://bitejiaoyan.oss-cn-chengdu.aliyuncs.com/bitehouse/web/common/default-house.png'
  // 图片加载失败
  const onError = (i) => {
    houseList.value[i].headImage = defaultImage
  }
</script>

<template>
  <!-- 顶部导航栏 -->
  <bit-nav-bar title="比特租房" />

  <!-- 筛选面板 -->
  <view class="filter-options">
    <view
      v-for="item in FILTER_LIST"
      :key="item.id"
      class="filter-options-item"
      @click="onOpen(item)"
    >
      <template>
        <text
          v-if="item.key === FILTER_MAP.AREA"
          class="filter-options-item-text"
          :class="{ active: item.isOpen || isRegionActive }"
          >{{ selectedRegion.name || item.name }}
        </text>
        <text
          class="filter-options-item-text"
          :class="{ active: item.isOpen || isRentPriceActive }"
          v-else-if="item.key === FILTER_MAP.RENT_PRICE"
          >{{ item.name }}</text
        >
        <text
          class="filter-options-item-text"
          :class="{ active: item.isOpen || isHouseTypeActive }"
          v-else-if="item.key === FILTER_MAP.HOUSE_TYPE"
          >{{ rentTypeName || item.name }}</text
        >
        <text
          class="filter-options-item-text"
          :class="{ active: item.isOpen || isSortActive }"
          v-else
          >{{ item.name }}</text
        >
      </template>

      <bit-icon
        v-if="item.isOpen"
        color="#0FA1FE"
        size="26"
        >&#xe6e8;</bit-icon
      >
      <bit-icon
        v-else
        color="#999"
        size="26"
        >&#xe6e9;</bit-icon
      >
    </view>
  </view>
  <!-- 房源列表 -->
  <scroll-view
    scroll-y
    class="filter-list no-scrollbar"
    @scrolltolower="onReachBottom"
  >
    <!-- 有内容 -->
    <template v-if="houseList.length > 0">
      <bit-house-item
        v-for="item in houseList"
        :key="item.houseid"
        :item="item"
        @error="onError"
      />
    </template>

    <!-- 无内容 -->
    <view
      class="filter-list-no-content"
      v-else-if="!isLoading"
    >
      <image
        src="https://bitejiaoyan.oss-cn-chengdu.aliyuncs.com/bitehouse/web/common/quesheng.png"
        mode="scaleToFill"
        class="filter-list-no-content__image"
      />
      <text class="filter-list-no-content__text">暂无内容</text>
    </view>
  </scroll-view>

  <!-- 弹出层 -->
  <bit-popup
    v-model="visible"
    :top="SCROLL_VIEW_TOP"
    :showConfirmButton="opsType !== FILTER_MAP.SORT"
    @confirm="onConfirm"
    @close="onPopupClose"
  >
    <filterByArea
      ref="areaRef"
      v-if="opsType === FILTER_MAP.AREA"
      :regionList="regionList"
    />
    <filterByPrice
      ref="priceRef"
      v-else-if="opsType === FILTER_MAP.RENT_PRICE"
      :rentRangeList="rentRangeList"
    />
    <filterByType
      ref="houseTypeRef"
      v-else-if="opsType === FILTER_MAP.HOUSE_TYPE"
      :rent-type-list="rentTypeList"
      :room-num-list="roomNumList"
      :current-rent-type="currentRentType"
    />
    <filterBySort
      v-else
      @change="onConfirm"
    />
  </bit-popup>
</template>

<style lang="scss" scoped>
  @import '@/styles/variable.scss';
  @import '@/styles/mixins.scss';
  // 筛选项
  .filter-options {
    position: fixed;
    left: 0;
    right: 0;
    top: 176rpx;
    width: 100vw;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 88rpx;
    padding: 0 50rpx;
    background: #fff;
    border-radius: 20rpx;
    &-item {
      &-text {
        font-size: var(--font-size-sm);
        color: var(--text-color-dark);
        &.active {
          color: var(--text-active-color);
        }
      }
    }
  }
  // 房源列表
  .filter-list {
    position: fixed;
    left: 0;
    right: 0;
    top: 284rpx;
    @include bottom-safeArea;
    width: 100vw;
    box-sizing: border-box;
    padding: 20rpx 30rpx;
    background-color: var(--main-bg-color);
    &-no-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 588rpx;
      height: 541rpx;
      margin: 85rpx 51rpx 0;
      padding-bottom: 47rpx;

      &__image {
        width: 100%;
      }
      &__text {
        font-size: var(--font-size-sm);
        color: var(--text-color-light);
      }
    }
  }
</style>
